package com.msmall.erp.sso.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.msmall.base.rms.po.Administer;
import com.msmall.erp.base.LoginConstant;
import com.msmall.erp.sso.manager.SSOManager;
import com.msmall.erp.sso.vo.AdministerVO;

@Controller
//@RequestMapping(value = "/ad")//表示要访问这个action的时候都要加上这个/ad路径  
public class LoginController {

	private static final Logger log = Logger.getLogger(LoginController.class);
	
	@Autowired
	private SSOManager ssoManager;
	
	/**
	 * 权限验证出错
	 * @return
	 */
	@RequestMapping("/rms/authError")
    public String authError() {
        return "rms.autherror";
    }
	
	@RequestMapping("/sso")
    public String sso() {
        return "site.login";
    }
	/* 接收参数getParameter()的时候: 
	 * 如果地址栏/springmvc/hello.htm上面没有传递参数,那么当id为int型的时候会报错,当id为Integer的时候值为null 
	 * 当地址栏为/springmvc/hello.htm?id=10的时候,action中有三种接收方式 
	 * 1、String hello(@RequestParam(value = "userid") int id),这样会把地址栏参数名为userid的值赋给参数id,如果用地址栏上的参数名为id,则接收不到 
	 * 2、String hello(@RequestParam int id),这种情况下默认会把id作为参数名来进行接收赋值 
	 * 3、String hello(int id),这种情况下也会默认把id作为参数名来进行接收赋值 
	 * 注:如果参数前面加上@RequestParam注解,如果地址栏上面没有加上该注解的参数,例如:id,那么会报404错误,找不到该路径 
	 */  
	@RequestMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response, HttpSession session, String username, @RequestParam String password, Map<String, String> module) {
		try{
			JSONObject json = ssoManager.validate(username, password);
			int returnCode = json.getInt(LoginConstant.RETURN_CODE_KEY);
			if(LoginConstant.RETURN_CODE_SUCCESS == returnCode){
				Administer administer = (Administer) json.get(LoginConstant.RETURN_KEY_ADMINISTER);
				AdministerVO vo = new AdministerVO();
				vo.setId(administer.getId());
				vo.setLogin(true);
				vo.setUsername(username);
				session.setAttribute(LoginConstant.HTTP_SESSION_KEY_ADMINISTER, vo);
				return "redirect:/mainMenu.do";
			}else if(LoginConstant.RETURN_CODE_FAILED_USERNAME == returnCode){
				module.put("message", "用户名错误");
				return "site.login";
			}else if(LoginConstant.RETURN_CODE_FAILED_PASSWORD == returnCode){
				module.put("message", "密码错误");
				return "site.login";
			}else {
				module.put("message", "系统错误");
				return "site.login";
			}
		}catch(Exception e){
			log.error(e);
			module.put("message", "系统错误");
			return "site.login";
		}
		
		
		/**
		 * return "forward:/order/add";

return "redirect:/index.jsp"; 
		 */
    }
}
